package com.yq.cns.ui.main.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fmt.mvi.learn.gobal.log
import com.yq.cns.ui.main.fragment.news.NewsFragment
import com.yq.cns.R
import com.yq.cns.entity.BottomNavigatorEntity
import com.yq.cns.ui.main.MainRepository
import com.yq.cns.ui.main.MainViewAction
import com.yq.cns.ui.main.MainViewState
import com.yq.cns.ui.main.fragment.MineFragment
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author: user
 * @date: 2022/11/16
 */
class MainViewModel constructor(): ViewModel() {


   val repository: MainRepository = MainRepository()

    private val _viewState = MutableStateFlow<MainViewState>(MainViewState.Loading)
    val state: StateFlow<MainViewState> = _viewState.asStateFlow()
    private val userIntent = MutableSharedFlow<MainViewAction>()



    init {

        viewModelScope.launch {
            userIntent.collect {
                when (it) {
                    is MainViewAction.GetBottomData -> getBottomData()
                }
            }
        }
    }


    private fun getBottomData() {
        viewModelScope.launch {
            kotlin.runCatching {
                repository.getBottomNavigatorData()
            }.onSuccess {
                _viewState.value = MainViewState.OnSuccess(it)
                "首页数据加载成功".log()
            }.onFailure {
                _viewState.value = MainViewState.Fail(it.message.toString())
            }
        }
    }


    fun dispatchEvent(action: MainViewAction) {
        viewModelScope.launch {
            userIntent.emit(action)
        }
    }


    var temp2 = 0;

}